package com.geniusk.system.controller;

import cn.hutool.core.util.StrUtil;
import com.geniusk.common.core.JSONResult;
import com.geniusk.common.utils.PageUtil;
import com.geniusk.common.utils.RedisUtil;
import com.geniusk.system.model.bo.online.ForceLogoutBO;
import com.geniusk.system.model.bo.online.SelectOnlineByPageBO;
import com.geniusk.security.annotation.PreFuncAuth;
import com.geniusk.security.core.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;

import static com.geniusk.security.constant.SecurityConstants.LOGIN_TOKEN_KEY;

/**
 * 登陆监控接口
 */
@RestController
@RequestMapping("/system/online")
public class OnlineController {

    @Autowired
    private RedisUtil redisCache;

    /**
     * 在线用户分页查询
     */
    @PostMapping("/selectOnlineByPage")
    @PreFuncAuth("MONITOR:ONLINE:SELECT")
    public JSONResult selectOnlineByPage(@Valid @RequestBody SelectOnlineByPageBO selectOnlineByPageBO){

        List<String> keyList = redisCache.getKeys(LOGIN_TOKEN_KEY + "*");
        List<LoginUser> list = new ArrayList<>();
        for (String key : keyList) {
            LoginUser loginUser = redisCache.getCacheObject(key);
            if(StrUtil.isNotBlank(selectOnlineByPageBO.getUsername())){
                if(StrUtil.equals(selectOnlineByPageBO.getUsername(),loginUser.getUsername())){
                    list.add(loginUser);
                }
            }else{
                list.add(loginUser);
            }
        }
        list.sort(Comparator.comparing(LoginUser :: getLoginTime).reversed());
        Integer pageNum = selectOnlineByPageBO.getPageNum();
        Integer pageSize = selectOnlineByPageBO.getPageSize();
        Map<String,Object> result = PageUtil.getResultTableData(list,pageNum,pageSize);
        return JSONResult.ok(result);
    }

    /**
     * 用户强退
     */
    @PostMapping("/forceLogout")
    @PreFuncAuth("MONITOR:ONLINE:FORCE")
    public JSONResult forceLogout(@Valid @RequestBody ForceLogoutBO forceLogoutBO) {
        boolean isForce = redisCache.deleteObject(LOGIN_TOKEN_KEY + forceLogoutBO.getIdentityId());
        Map<String, Object> result = new HashMap<>();
        result.put("isForce",isForce);
        return JSONResult.ok(result);
    }
}